<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <div slot="toolbar">
            <a-button icon="link" @click="testConnect2">
                {{i18n('list.testCon','测试连接')}}
            </a-button>
        </div>
        <rx-layout>
            <div slot="center">
                <a-form :form="form">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['id']"/>
                    </a-form-item>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.datasourceName','数据源名称')" >
                                <a-input :placeholder="i18n('form.datasourceName','数据源名称','input')"
                                         v-decorator="['name', {rules: [{required: true, message: i18n('form.datasourceName','数据源名称','input')}]}]"

                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.alias','别名')">
                                <a-input :placeholder="i18n('form.alias','别名')"
                                         v-decorator="['alias', {rules: [{required: true, message: i18n('form.alias','别名','input')}]}]">

                                </a-input>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-if="appMode!='single'">
                        <a-col :span="24">
                            <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                                <span slot="label"><span style="color: red">* </span>{{i18n('form.Microservices','微服务')}}
                                    <a-tooltip slot="suffix" :title="i18n('form.serviceTipInfo','勾选的微服务可使用该数据源')">
                                        <a-icon type="question-circle" />
                                    </a-tooltip>
                                </span>
                                <a-checkbox-group  :options="plainOptions" v-model="checkedList" />

                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.DBType','数据库类型')">
                                <a-select :placeholder="i18n('form.DBType','数据库类型')"
                                          v-decorator="['dbType', {rules: [{required: false, message: i18n('form.DBType','数据库类型','select')}]}]"
                                          @change="dbTypeChange">
                                    <a-select-option value="mysql">MySql</a-select-option>
                                    <a-select-option value="sqlserver">SqlServer</a-select-option>
                                    <a-select-option value="oracle">Oracle</a-select-option>
                                    <a-select-option value="dm">DM(达梦)</a-select-option>
                                    <a-select-option value="postgresql">PostgreSql</a-select-option>
                                    <a-select-option value="kingbase">Kingbase</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.isEnable','是否使用')">
                                <a-checkbox :placeholder="i18n('form.isEnable','是否使用')" :checked="mdl.enable" @change="onChange($event,'enable')"
                                            v-decorator="['enable', {rules: [{required: false, message: i18n('form.isEnable','是否使用')}]}]"></a-checkbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.encrypt','是否加密')">
                                <a-checkbox v-show="!isShowCheckBox" :placeholder="i18n('form.encrypt','是否加密')" :checked="mdl.encrypt" @change="onEncryptChange"
                                            v-decorator="['encrypt', {rules: [{required: false, message: i18n('form.encrypt','是否加密')}]}]"></a-checkbox>
                                <span v-show="isShowCheckBox">{{$comi18('rxDialog.yes', "是")}}</span>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
<!--                        <a-col :span="12">-->
<!--                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否租户使用">-->
<!--                                <a-checkbox v-model="isTenant"></a-checkbox>-->
<!--                            </a-form-item>-->
<!--                        </a-col>-->
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <rx-grid ref="table"
                                     :dataSource="fields"
                                     :showPage="false"
                                     :enableHtmlEscape="false"
                                     :activeEditFun="activeEditFun"
                                     :columns="columns"
                                     :heightauto="true"
                                 >
                                 <span slot="val" slot-scope="{text, record,index,blur}">
                                   <a-input-password v-if="record.name=='password'" v-model="record.val" @blur="passwordEncrypt(record)" @click="clearData(record)"/>
                                  <a-input v-else v-model="record.val" @blur="blur(index,'val',text,record)"/>
                                 </span>
                            </rx-grid>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormDataSourceDefApi from '@/api/form/core/formDataSourceDef'
import PublicApi from '@/api/form/core/public'
import {BaseForm, RxDialog, RxGrid} from "@lowcode/jpaas-common-lib";
import {mapState} from 'vuex';

export default {
    name: 'FormDataSourceDefEdit',
    mixins: [BaseForm],
    components: {
        RxDialog,
        RxGrid
    },
    computed: {
        ...mapState({
            appMode: state => state.appSetting.appMode,
        })
    },
    data() {
        return {
            checkedList: [],
            plainOptions: [],
            fields: [],
            columns: [{title: this.i18n('form.paramName','参数名'), dataIndex: 'name', width: 100},
                {title: this.i18n('form.paramDesc','参数说明'), dataIndex: 'comment', width: 100},
                {title: this.i18n('form.paramType','参数类型'), dataIndex: 'type', width: 50},
                {title: this.i18n('form.paramVal','参数值'), dataIndex: 'val', allowCellEdit: true, scopedSlots: {customRender: 'val'}, width: 400}],
            defaultFields: [{
                name: "url",
                comment: this.i18n('form.connAddress','连接字符串'),
                type: "String",
                val: "jdbc:mysql://localhost:3306/dbName?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8"
            },
                {name: "username", comment: this.defaultI18n('username',"用户名"), type: "String", val: ""},
                {name: "password", comment: this.defaultI18n('password',"密码"), type: "String", val: ""},
                {name: "driverClassName", comment: this.defaultI18n('driverClassName',"驱动类"), type: "String", val: "com.mysql.cj.jdbc.Driver"},
                {name: "connectionInitSqls", comment: this.defaultI18n('connectionInitSqls',"初始执行sql"), type: "String", val: ""},
                {name: "initialSize", comment: this.defaultI18n('initialSize',"初始大小"), type: "int", val: "5"},
                {name: "minIdle", comment: this.defaultI18n('minIdle',"最小空闲连接数"), type: "int", val: "5"},
                {name: "maxActive", comment: this.defaultI18n('maxActive',"连接池最大数"), type: "int", val: "10"},
                {name: "maxWait", comment: this.defaultI18n('maxWait',"获取连接超时的时间(毫秒)"), type: "long", val: "60000"},
                {name: "timeBetweenEvictionRunsMillis", comment: this.defaultI18n('timeBetweenEvictionRunsMillis',"检测间隔时间(毫秒)"), type: "long", val: "60000"},
                {name: "minEvictableIdleTimeMillis", comment: this.defaultI18n('minEvictableIdleTimeMillis',"连接最小生存时间(毫秒)"), type: "long", val: "300000"},
                {name: "validationQuery", comment: this.defaultI18n('validationQuery',"连接校验语句"), type: "String", val: "SELECT 1 "},
                {name: "testWhileIdle", comment: this.defaultI18n('testWhileIdle',"空闲时检测连接"), type: "boolean", val: "true"},
                {name: "testOnBorrow", comment: this.defaultI18n('testOnBorrow',"获取连接时检测连接"), type: "boolean", val: "false"},
                {name: "testOnReturn", comment: this.defaultI18n('testOnReturn',"连接返回连接池时检测连接"), type: "boolean", val: "false"},
                {name: "poolPreparedStatements", comment: this.defaultI18n('poolPreparedStatements',"打开PSCACHE"), type: "boolean", val: "true"},
                {name: "maxPoolPreparedStatementPerConnectionSize", comment: this.defaultI18n('maxPoolPreparedStatementPerConnectionSize',"PSCACHE大小"), type: "int", val: "20"},
                {name: "filters", comment: this.defaultI18n('filters',"插件"), type: "String", val: "stat,config"},
                {name: "connectProperties", comment: this.defaultI18n('connectProperties',"连接配置"), type: "Properites", val:"config.decrypt=false"}],
            isTenant: false,
            //是否显示单选框
            isShowCheckBox:false,
            //是否加密
            isEncrypt:false,
        }
    },
    created() {
        this.initAppService();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formDS",key);
        },
        defaultI18n(name,text,key){
            return this.$ti18("defaultFields."+name,text,"formDS",key);
        },
        initAppService() {
            PublicApi.getAppServices().then(res => {
                this.plainOptions = res;
            });
        },
        //清除密码输入框数据
        clearData(record){
            record.val = "";
        },
        //对密码进行加密
        passwordEncrypt(record){
            //控制编辑状态
            record.val_editable = false;
            //判断当前是否加密
            if(!this.isEncrypt){
                return;
            }
            var table = this.$refs.table;
            var rows = table.findRows(function (row) {
                if (row.name=="password" || row.name == "connectProperties") {
                    return true;
                }
            });
            var encrypt=true;
            FormDataSourceDefApi.getPassword(rows[0].val,encrypt).then(res=>{
                table.updateRow(rows[0], {val: res.data});
            })
        },
        get(id) {
            return FormDataSourceDefApi.get(id);
        },
        save(values,vm) {
            if (this.checkedList.length==0 && this.appMode!='single'){
                this.$message.error(this.i18n('form.Microservices','微服务列表','select'))
                vm.loading=false
                return ;
            }
            values.setting = JSON.stringify(this.$refs.table.getData());
            if(this.appMode!='single'){
                values.appName = this.checkedList.join(",");
            }else{
                values.appName = this.plainOptions.join(",");
            }

            if (this.isTenant) {
                values.isTenant = "1";
            } else {
                values.isTenant = "0";
            }
            return FormDataSourceDefApi.save(values);
        },
        //测试连接
        testConnect2() {
            this.form.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    values.setting = JSON.stringify(this.$refs.table.getData());
                    if(this.appMode!='single'){
                      values.appName = this.checkedList.join(",");
                    }else{
                      values.appName = this.plainOptions.join(",");
                    }
                    FormDataSourceDefApi.testConnect2(values);
                }
            );
        },
        onload_(data) {
            if (data) {
                this.fields = JSON.parse(data.setting);
                this.parseBoolean(data, "enable");
                this.parseBoolean(data, "encrypt");
                this.parseBoolean(data, "initOnStart");
                //如果当前是加密状态
                if(data.encrypt){
                    this.isShowCheckBox = true;
                }
                if (data.appName && this.appMode!='single') {
                    this.checkedList = data.appName.split(",");
                }
                if (data.isTenant && data.isTenant == "1") {
                    this.isTenant = true;
                }
            } else {
                this.fields = this.defaultFields;
                this.mdl = Object.assign({enable: true,encrypt:false, initOnStart: true, dbType: 'mysql'});
                //表单默认值
                this.form.setFieldsValue(this.mdl);
            }
        },
        parseBoolean(data, bl) {
            if (data[bl] == "true") {
                data[bl] = true;
            } else {
                data[bl] = false;
            }
        },
        activeEditFun(col,row){
            if(col.column.dataIndex=='val' && row.index==2 && this.mdl.encrypt){
                return true;
            }
            return true;
        },
        onEncryptChange(e){
            var table = this.$refs.table;
            var rows = table.findRows(function (row) {
                if (row.name=="password" || row.name == "connectProperties") {
                    return true;
                }
            });
            var encrypt=e.target.checked;
            //如果勾选了加密
            if(encrypt){
                this.isEncrypt = true;
            }else{
                this.isEncrypt = false;
            }
            FormDataSourceDefApi.getPassword(rows[0].val,encrypt).then(res=>{
                table.updateRow(rows[0], {val: res.data});
            })
            if(rows.length==1){
                this.fields.push({name: "connectProperties", comment: this.i18n('form.connConfig','连接配置'), type: "Properites", val:"config.decrypt=" + encrypt});
            }else {
                let val=rows[1].val;
                let ary=val.split(";");
                for(let i=0;i<ary.length;i++){
                    let config=ary[i].split("=");
                    if(config[0]=='config.decrypt'){
                        config[1]=encrypt;
                    }
                    ary[i]=config.join("=");
                }
                table.updateRow(rows[1], {val: ary.join(";")});
            }
            this.onChange(e,'encrypt');
        },
        onChange(e, type) {
            this.mdl[type] = e.target.checked;
        },
        dbTypeChange(val) {
            let url = "";
            let driveClassName = "";
            let connectionInitSqls = "";
            let validationQuery = "SELECT 1 ";
            if (val == "mysql") {
                url = "jdbc:mysql://localhost:3306/dbName?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8";
                driveClassName = "com.mysql.cj.jdbc.Driver";
            } else if (val == "sqlserver") {
                url = "jdbc:sqlserver://localhost:1433;DatabaseName=dbname;integratedSecurity=false";
                driveClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            } else if (val == "oracle") {
                url = "jdbc:oracle:thin:@localhost:1521:orcl";
                driveClassName = "oracle.jdbc.driver.OracleDriver";
                validationQuery = "SELECT 1 FROM dual";
            } else if (val == "dm") {
                url = "jdbc:dm://localhost:5236/dbName?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8";
                driveClassName = "dm.jdbc.driver.DmDriver";
                connectionInitSqls = "SET SCHEMA dbName";
            } else if (val == "postgresql") {
                url = "jdbc:postgresql://localhost:5432/dbName";
                driveClassName = "org.postgresql.Driver";
            } else if (val == "kingbase") {
                url = "jdbc:kingbase8://localhost:54321/dbName";
                driveClassName = "com.kingbase8.Driver";
            }
            var table = this.$refs.table;
            var rows = table.findRows(function (row) {
                if (row.name == "url" || row.name == "driverClassName" || row.name == "connectionInitSqls" || row.name == "validationQuery") {
                    return true;
                }
            });
            table.updateRow(rows[0], {val: url});
            table.updateRow(rows[1], {val: driveClassName});
            table.updateRow(rows[2], {val: connectionInitSqls});
            table.updateRow(rows[3], {val: validationQuery});
        }
    },
    watch: {
        "mdl.isTenant": function (val) {

        }
    }
}
</script>
